#!/usr/bin/perl -w
use strict;

my $annotation_file = $ARGV[0];
my $prediction_file = $ARGV[1];

my %pmid_terms;
my %pmid_count;
&read_annotations;

&read_predictions;

sub read_annotations{ 
	open (FD, $annotation_file) ||
		die ("Unable to open: $annotation_file\n");
	while (<FD>){ 
		chop;
		my ($pmid, $term) = split (/\t/, $_);
		$pmid_terms{$pmid . "-" . $term} = 1;
		if (not exists($pmid_count{$pmid})){
			$pmid_count{$pmid} = 1;	
		} else { 
			$pmid_count{$pmid} += 1;	
		}	
		# print $pmid . "-" . $term . "\n";
	}	
	close (FD);		
}

sub read_predictions{ 

	my $prev_pmid = "";
	my $fp = 0;
	my $tp = 0;
	my %local_ids;
	my $gt = 0;
	my $gtp = 0;
	my $gfp = 0;
	open (FD, $prediction_file) ||
		die ("Unable to open: $prediction_file\n");
	while (<FD>){ 
		chop;
			
		my @tfs = split (/\t/, $_);
		$tfs[0] =~ s/\.txt//;
		if ($prev_pmid ne $tfs[0] and $prev_pmid ne ""){ 
			my $total = 0;	
			if (exists($pmid_count{$prev_pmid})){
				$total = $pmid_count{$prev_pmid};	
			}
			$gt += $total;
			$gfp += $fp;
			$gtp += $tp;

			my $fn = $total - $tp;
			if ($fn < 0){ $fn = 0; }				
			print $prev_pmid . " ";
			print $total . " ";
			print $tp . " ";
			print $fp . " ";
			print $fn . "\n";
			$fp = 0;			
			$tp = 0;			
			$fn = 0;
			undef %local_ids;		
		}
		
		$prev_pmid = $tfs[0];	
		my @ids = split (/\,/, $tfs[4]);
		for (my $k = 0; $k < scalar(@ids); $k++){ 
			# print $tfs[0] . "-" . $ids[$k] . "\n";
			next if (exists($local_ids{$ids[$k]}));
			$local_ids{$ids[$k]} = 1;
			if (exists($pmid_terms{$tfs[0] ."-" . $ids[$k]})){ 
				$tp++;
			} else{ 
				# print $tfs[4] . "  " . $tfs[3] . "\n";
				$fp++;
			}
		}		
	}	
	close (FD);		
	
	print $gt . " " . $gtp . " " . $gfp . " " . ($gt - $gtp) . "\n";
}
